package com.junmo.oauth.config.handler;


import com.junmo.oauth.module.system.entity.SysUser;
import com.junmo.oauth.utils.JwtTokenUtil;
import com.junmo.oauth.utils.R;
import com.junmo.oauth.utils.ResponseUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理类
 */
@Component
@Slf4j
@AllArgsConstructor
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private RestTemplate restTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        log.info("================"+ JSON.toJSONString(authentication));
//        SysUser sysUser =  (SysUser) authentication.getPrincipal();
//        String token = jwtTokenUtil.generateToken(sysUser);
        DefaultOAuth2AccessToken defaultOAuth2AccessToken =  getToken();
        // 封装返回参数
        ResponseUtil.writeMsg(response, R.success("登录成功",defaultOAuth2AccessToken.toString()));
    }

    public DefaultOAuth2AccessToken  getToken(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("grant_type", "password");
        requestBody.add("client_id", "clientId");
        requestBody.add("client_secret", "123456");
        requestBody.add("username", "admin");
        requestBody.add("password", "123456");
        DefaultOAuth2AccessToken defaultOAuth2AccessToken = restTemplate.postForEntity("http://localhost:8081/oauth/token", new HttpEntity<>(requestBody,headers), DefaultOAuth2AccessToken.class).getBody();
        return  defaultOAuth2AccessToken;
    }

}
